package com.ftw.commons

import android.annotation.TargetApi
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.Window.FEATURE_NO_TITLE
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import com.ftw.commons.language.LocalManageUtil
import com.ftw.commons.receiver.NetWorkChangeReceiver
import com.ftw.commons.utils.ScreenUtils
import com.ftw.commons.utils.StatusBarUtils
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import com.trello.rxlifecycle3.components.support.RxFragment
import kotlinx.android.synthetic.main.activity_common.*


/**
 * 描    述：
 * 作    者：fantianwen
 * 时    间：2019/2/12  10:10 AM
 */
abstract class BaseActivity : RxAppCompatActivity() {

    private val REQUEST_CODE = 319
    private var mNetWorkChangeReceiver: NetWorkChangeReceiver? = null

    /**
     * 初始化页面Ui等元素
     */
    abstract fun initView()

    /**
     * 子布局
     */
    abstract fun getViewId(): Int

    @TargetApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        supportRequestWindowFeature(FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        ScreenUtils.fixOrientation(this)
        overridePendingTransition(R.anim.right_enter, R.anim.left_exit)
        BaseApplication.addActivity(this)
        setContentView(R.layout.activity_common)
        StatusBarUtils.setStatusBarFontColor(this)
        if (getViewId() != 0) {
            val view = LayoutInflater.from(this)
                .inflate(getViewId(), null)
            fragment_container.addView(view)
        }

        initNetWorkListener()
        initView()

    }

    override fun onDestroy() {
        super.onDestroy()
        BaseApplication.removeActivity(this)
        unregisterReceiver(mNetWorkChangeReceiver)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode == Activity.RESULT_CANCELED && REQUEST_CODE == requestCode) {
            true -> {
                val intent = Intent(Intent.ACTION_MAIN)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.addCategory(Intent.CATEGORY_HOME)
                startActivity(intent)
                finish()
            }
        }
    }

    /**
     * 批量加载fragment
     */
    fun loadFragment(vararg fragments: RxFragment, showPosition: Int, resourceId: Int) {

        if (fragments.isEmpty()) {
            return
        }

        supportFragmentManager.beginTransaction().apply {
            for (index in fragments.indices) {
                val fragment = fragments[index]
                add(resourceId, fragment, fragment::class.java.simpleName)
                when (showPosition == index) {
                    true -> {
                        setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
                    }
                    else -> {
                        hide(fragment)
                        setMaxLifecycle(fragment, Lifecycle.State.STARTED)
                    }
                }
            }
        }.commitAllowingStateLoss()
    }

    /**
     * 替换或加载fragment
     * @param fragment
     * @param addToBackStack
     */
    fun loadFragment(fragment: RxFragment, addToBackStack: Boolean) {
        supportFragmentManager.beginTransaction().apply {
            add(R.id.fragment_container, fragment, fragment.javaClass.name)
            if (addToBackStack) {
                addToBackStack(null)
            }
        }.commitAllowingStateLoss()
    }


    fun showFragment(
        resourceId: Int,
        fragmentTag: String,
        showFragment: Fragment,
        addToBackStack: Boolean
    ) {

        supportFragmentManager
            .beginTransaction()
            .apply {
                supportFragmentManager.findFragmentByTag(fragmentTag)?.let {
                    show(showFragment)
                } ?: let {
                    add(resourceId, showFragment, fragmentTag)
                    if (addToBackStack) {
                        addToBackStack(null)
                    }
                }

                setMaxLifecycle(showFragment, Lifecycle.State.RESUMED)

                val fragments = supportFragmentManager.fragments

                fragments
                    .filter { it != showFragment }
                    .forEach {
                        hide(it)
                        setMaxLifecycle(it, Lifecycle.State.STARTED)
                    }
            }.commitAllowingStateLoss()
    }

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(LocalManageUtil.setLocal(newBase!!))
    }

    /**
     * 初始化网络监听
     */
    private fun initNetWorkListener() {
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        mNetWorkChangeReceiver = NetWorkChangeReceiver()
        registerReceiver(mNetWorkChangeReceiver, intentFilter)
    }


    /**
     * =================================activity权限请求代码=====================================
     */
    /**
     * 权限请求结果回调接口
     */
    interface RequestPermissionCallBack {
        /**
         * 同意授权
         */
        fun granted()

        /**
         * 取消授权
         */
        fun denied()
    }

    private var mRequestPermissionCallBack: RequestPermissionCallBack? = null

    private val mRequestCode = 1024

    /**
     * 发起权限请求
     *
     * @param context
     * @param permissions
     * @param callback
     */
    fun requestPermissions(
        context: Context, permissions: Array<String>,
        callback: RequestPermissionCallBack
    ) {
        this.mRequestPermissionCallBack = callback
        var permissionNames = StringBuilder()
        for (s in permissions) {
            permissionNames = permissionNames.append(s + "\r\n")
        }
        //如果所有权限都已授权，则直接返回授权成功,只要有一项未授权，则发起权限请求
        var isAllGranted = true
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    context,
                    permission
                ) == PackageManager.PERMISSION_DENIED
            ) {
                isAllGranted = false

                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        context as Activity,
                        permission
                    )
                ) {
                    ActivityCompat.requestPermissions(
                        (context),
                        permissions,
                        mRequestCode
                    )
                } else {
                    ActivityCompat.requestPermissions((context), permissions, mRequestCode)
                }

                break
            }
        }
        if (isAllGranted) {
            mRequestPermissionCallBack?.granted()
            return
        }
    }

    /**
     * 权限请求结果回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var hasAllGranted = true
        var permissionName = StringBuilder()
        for (s in permissions) {
            permissionName = permissionName.append(s + "\r\n")
        }
        when (requestCode) {
            mRequestCode -> {
                for (i in grantResults.indices) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        hasAllGranted = false
                        //在用户已经拒绝授权的情况下，如果shouldShowRequestPermissionRationale返回false则
                        // 可以推断出用户选择了“不在提示”选项，在这种情况下需要引导用户至设置页手动授权
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                permissions[i]
                            )
                        ) {
                            AlertDialog.Builder(this)
                                .setMessage(
                                    getString(
                                        R.string.string_permission_msg,
                                        permissionName
                                    )
                                )
                                .setPositiveButton(
                                    getString(R.string.string_to_authorize)
                                ) { _, _ ->
                                    val intent =
                                        Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                                    val uri = Uri.fromParts(
                                        "package",
                                        applicationContext.packageName,
                                        null
                                    )
                                    intent.data = uri
                                    startActivity(intent)
                                }
                                .setNegativeButton(
                                    getString(R.string.cancel)
                                ) { _, _ -> mRequestPermissionCallBack?.denied() }
                                .setOnCancelListener { mRequestPermissionCallBack?.denied() }.show()

                        } else {
                            //用户拒绝权限请求，但未选中“不再提示”选项
                            mRequestPermissionCallBack?.denied()
                        }
                        break
                    }
                }
                if (hasAllGranted) {
                    mRequestPermissionCallBack?.granted()
                }
            }
        }
    }

    open fun getVisibleFragment(): Fragment? {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragments: List<Fragment> = fragmentManager.fragments
        for (fragment in fragments) {
            if (fragment.isVisible) return fragment
        }
        return null
    }


}